package servlet;

import bean.Result;
import com.google.gson.Gson;
import dao.PhoneManageDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Map;
// zpl
@WebServlet(name = "QueryPhoneServlet", value = "/QueryPhoneServlet.s")
public class QueryPhoneServlet extends HttpServlet {
    private PhoneManageDao dao = new PhoneManageDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        Result res;
        try {
            String product = request.getParameter("product");
            String type = request.getParameter("type");
            String price = request.getParameter("price");
            String currentPage = request.getParameter("currentPage");
            String pageSize = request.getParameter("pageSize");

            System.out.println(product);
            System.out.println(type);
            System.out.println(price);
            int page = Integer.valueOf(currentPage);
            int size = Integer.valueOf(pageSize);
            Map<String, Object> map;
            if (price != null && price.trim().isEmpty() == false){
                String[] split = price.split("~");
                map = dao.query(product, type, split[0], split[1], page, size);
            }else {
                map = dao.query(product, type, null, null, page, size);
            }

            res = new Result(1, "查询成功!", map);
        } catch (Exception e) {
            e.printStackTrace();
            res = new Result(0, "查询失败!", null);
        }
        String json = new Gson().toJson(res);
        response.getWriter().append(json);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request,response);
    }
}
